<?php

namespace Addons\Journal\Controller;
use Home\Controller\AddonsController;

class JournalController extends AddonsController{
	public function lists() {
		$this->assign ( 'add_button', false );
		//$this->assign ( 'del_button', false );
		//$this->assign ( 'check_all', false );
		
		$model = $this->getModel ( 'weixin_log' );
		$page || $page = I ( 'p', 1, 'intval' ); // 默认显示第一页数据
		                                         
		// 解析列表规则
		$list_data = $this->_list_grid ( $model );
		$grids = $list_data ['list_grids'];

		$fields = $list_data ['fields'];
		
		// 搜索条件
		$map = $this->_search_map ( $model, $fields );
		
		$row = empty ( $model ['list_row'] ) ? 20 : $model ['list_row'];
		
		// 读取模型数据列表
		if ($model ['extend']) {
			$name = get_table_name ( $model ['id'] );
			$parent = get_table_name ( $model ['extend'] );
			$fix = C ( "DB_PREFIX" );
			
			$key = array_search ( 'id', $fields );
			if (false === $key) {
				array_push ( $fields, "{$fix}{$parent}.id as id" );
			} else {
				$fields [$key] = "{$fix}{$parent}.id as id";
			}
			
			/* 查询记录数 */
			$count = M ( $parent )->join ( "INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id" )->where ( $map )->count ();
			
			// 查询数据
			$data = M ( $parent )->join ( "INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id" )->field ( empty ( $fields ) ? true : $fields )->where ( $map )->order ( "{$fix}{$parent}.{$order}" )->page ( $page, $row )->select ();
		} else {
			empty ( $fields ) || in_array ( 'id', $fields ) || array_push ( $fields, 'id' );
			$name = parse_name ( get_table_name ( $model ['id'] ), true );
			$map['ToUserName'] = get_token();
			$data = M ( $name )->where ( $map )->order('id DESC')->page ( $page, $row )->select ();
			foreach ( $data as $key => $val ) {
			 $data[$key]['cData'] = htmlspecialchars($val['cData']);
			}

			//dump($data);
			/* 查询记录总数 */
			$count = M ( $name )->where ( $map )->count ();
		}
		$list_data ['list_data'] = $data;
		
		// 分页
		if ($count > $row) {
			$page = new \Think\Page ( $count, $row );
			$page->setConfig ( 'theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%' );
			$list_data ['_page'] = $page->show ();
		}
		
		$this->assign ( $list_data );
		 //dump($list_data);exit;
		
		$this->display ();
	}
	
	public function clear() {
		$ctime = mktime(0,0,0,date("m"),date("d")-5,date("Y"));
		$token = get_token(); 
		if (I('get.type')=='all'){
			$res = M('weixin_log')->where( "token='$token'")->delete();
		}else{
			$res = M('weixin_log')->where( "token='$token' and cTime <= '$ctime'")->delete();
		}
		if($res){
			$this->success('清理完成！',U('lists'));
		}else{
			$this->error ( '已经清理过了！',U('lists') );
		}
	}
	
	public function del() {
		$model = $this->getModel ( 'weixin_log' );
		parent::common_del ( $model, $ids );
	}
}
